package com.liveinstars.demo;

import com.alibaba.fastjson.JSON;
import com.liveinstars.api.demo.HelloService;
import com.liveinstars.api.demo.model.HelloEnum;
import com.liveinstars.api.demo.model.HelloReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by guoyanjiang on 2018/11/26.
 */
@RestController
public class ConsumerController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    HelloService helloService;

    //restTemplate示例
    @GetMapping("/consumer/template/hello")
    public String consumerHelloByTremplate() {
        return restTemplate.getForEntity("http://provider-demo/hello?str=template", String.class).getBody();
    }

    //feign示例
    @GetMapping("/consumer/feign/hello")
    public String consumerHelloByFeign() {
        return helloService.hello("feign client");
    }

    @GetMapping("/consumer/feign/helloworld")
    public Object consumerHelloWorldByFeign() {
        return helloService.helloWorld(HelloReq.mock());
    }

    @GetMapping("/consumer/feign/hello/mix")
    public Object consumerHelloMixByFeign() {
        return helloService.helloMix(HelloReq.mock(), "single 123");
    }

    @GetMapping("/consumer/feign/hello/fastjson")
    public Object consumerHelloFasjjsonByFeign() {
        return helloService.helloFastjson(JSON.parseObject(HelloReq.mock().toString()), "single 123");
    }

    @GetMapping("/consumer/feign/test-boolean")
    public boolean consumerBooleanByFeign() {
        boolean flag = helloService.testBoolean();
        logger.info("consumer get boolean result {}", flag);
        return flag;
    }

    @GetMapping("/consumer/feign/test-void")
    public void consumerVoidByFeign() {
        helloService.testVoid();
        logger.info("consumer test void done");
    }

    @GetMapping("/consumer/feign/test-int")
    public int consumerIntByFeign(){
        return helloService.testInt(3);
    }

    @GetMapping("/consumer/feign/test-enum")
    public HelloEnum consumerEnumByFeign(){
        return helloService.testEnum(HelloEnum.CP_1day);
    }

    //确实不支持分布式的回调函数，想太多
//    @GetMapping("/consumer/feign/test-callback")
//    public void consumerCallBackByFeign(){
//        helloService.testCallBack(() -> logger.info("write log in call back"));
//    }

    @GetMapping("/consumer/feign/test-exception")
    public void consumerException(){
        helloService.testException();
    }
}
